import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:animation/components/appbar_base.dart';
import 'package:animation/generated/l10n.dart';
import 'package:animation/tools/down_image.dart';

class CacheClean extends StatefulWidget {
  const CacheClean({super.key});

  @override
  State<CacheClean> createState() => _CacheCleanState();
}

class _CacheCleanState extends State<CacheClean> {
  String cacheSize = '计算中';
  void getCacheSize() async {
    double size = await DownImage.getTotalCacheSize();
    setState(() {
      // 保留两位小数
      cacheSize = size.toStringAsFixed(2);
    });
  }

  @override
  void initState() {
    getCacheSize();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppbarBase(title: S.of(context).a13),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Flex(
          direction: Axis.vertical,
          children: [
            Material(
                color: Theme.of(context).colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(8),
                clipBehavior: Clip.antiAlias,
                child: ListTile(
                  title: Text(S.of(context).a14),
                  // 右侧图标
                  trailing: Text('$cacheSize MB'),
                  onTap: () {
                    showCupertinoDialog(
                      //点击空白处取消
                      barrierDismissible: true,
                      context: context,
                      builder: (context) {
                        return CupertinoAlertDialog(
                          title: Text(S.of(context).s8),
                          content: Padding(
                            padding: const EdgeInsets.only(top: 8),
                            child: Text(S.of(context).s9),
                          ),
                          actions: [
                            CupertinoDialogAction(
                              child: Text(S.of(context).s10),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                            CupertinoDialogAction(
                              child: Text(S.of(context).s11),
                              onPressed: () {
                                DownImage.clearAllCache();
                                setState(() {
                                  cacheSize = '0.0';
                                });
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      },
                    );
                  },
                ))
          ],
        ),
      ),
    );
  }
}
